package com.rachel.studyapp.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.rachel.studyapp.R;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhengshaorui on 2017/8/18.
 */

public class CusViewPagerForHome extends RelativeLayout implements ViewPager.OnPageChangeListener, View.OnTouchListener {
    private static final String TAG = "zsr";
    private ViewPager mViewPager;
    private Context mContext;
    private LinearLayout mLinearLayout;
    private static final int LOOP_COUNT = 5000;
    private static final int LOOP_START = 1;
    private static final int LOOP_TIME = 1000;
    private int mCurrentPageId;
    private List<View> mPointLists = new ArrayList<>();
    public CusViewPagerForHome(Context context) {
        this(context,null);
    }

    public CusViewPagerForHome(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public CusViewPagerForHome(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        View view = LayoutInflater.from(context).inflate(R.layout.banner_layout,null);
        addView(view);
        mViewPager = (ViewPager) view.findViewById(R.id.banner_viewpager);
        mLinearLayout = (LinearLayout) view.findViewById(R.id.banner_indeticor);

        mViewPager.setOnTouchListener(this);

    }

    public void setLoopStatus(boolean isLoop){
        if (!isLoop){
            mHandler.removeMessages(LOOP_START);
        }else{
            mHandler.sendEmptyMessage(LOOP_START);
        }
    }


    @Override
    protected void onVisibilityChanged(View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);
        if (visibility == VISIBLE){
            mHandler.sendEmptyMessageDelayed(LOOP_TIME,LOOP_START);
        }else{
            mHandler.removeMessages(LOOP_START);
        }

    }

    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case LOOP_START:
                    //这里重新获取一下 id，防止手动滑动而导致位置错乱
                    mCurrentPageId = mViewPager.getCurrentItem();
                    if (mCurrentPageId > LOOP_COUNT /2 ){
                        mViewPager.setCurrentItem(++mCurrentPageId);
                    }
                    if (mCurrentPageId > LOOP_COUNT){
                        mCurrentPageId = LOOP_COUNT+1;
                    }
                    mHandler.sendEmptyMessageDelayed(LOOP_START,LOOP_COUNT);
                    break;
            }
        }
    };


    public void setDatas(List<View> lists){

        if (mViewPager != null) {
            mViewPager.setAdapter(new AutoAdapter(lists));
            mViewPager.setCurrentItem(lists.size()+LOOP_COUNT/2);
            mCurrentPageId = lists.size()+LOOP_COUNT/2;
            initPoint(lists);

            mViewPager.addOnPageChangeListener(this);
            setViewScrollTime(mContext,mViewPager,500);
            mHandler.sendEmptyMessageDelayed(LOOP_START,LOOP_TIME);
        }
    }

    private void initPoint(List<View> lists) {

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        params.setMargins(15,0,0,0);
        for (int i = 0; i < lists.size(); i++) {
            ImageView imageView = new ImageView(mContext);
            imageView.setImageResource(R.drawable.pointselector);
            imageView.setLayoutParams(params);
            if (i == 0){
                imageView.setSelected(true);
            }else{
                imageView.setSelected(false);
            }
            mPointLists.add(imageView);
            mLinearLayout.addView(imageView);
            
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        for (int i = 0; i < mPointLists.size(); i++) {
            View view = mPointLists.get(i);
            if (i == (position % mPointLists.size())){
                view.setSelected(true);
            }else{
                view.setSelected(false);
            }

        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                mHandler.removeMessages(LOOP_START);
                break;
            case MotionEvent.ACTION_UP:
                //手指抬起3s后，仍没有再次按下，则启动轮播
                mHandler.sendEmptyMessageDelayed(LOOP_START,3000);
                break;
        }
        return false;
    }


    class AutoAdapter extends PagerAdapter {
        List<View> datas;

        public AutoAdapter(List<View> datas) {
            this.datas = datas;
        }

        @Override
        public int getCount() {
            return datas.size() + LOOP_COUNT;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = datas.get(position % datas.size());
            //Log.d(TAG, "instantiateItem: "+view);
            ViewGroup parent = (ViewGroup) view.getParent();
            if (parent != null) {
                parent.removeAllViews();
            }
            container.addView(view);
            return view;
        }
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);

        }
    }

    /**
     * 魅族效果
     */
    class ZoomOutPageTransformer implements ViewPager.PageTransformer {
        private static final float MAX_SCALE = 1.0f;
        private static final float MIN_SCALE = 0.9f;//0.85f

        @Override
        public void transformPage(View view, float position) {
            //setScaleY只支持api11以上
            if (position < -1) {
                // view.setScaleX(MIN_SCALE);
                view.setScaleY(MIN_SCALE);
            } else if (position <= 1) //a页滑动至b页 ； a页从 0.0 -1 ；b页从1 ~ 0.0
            { // [-1,1]
//              Log.e("TAG", view + " , " + position + "");
                float scaleFactor = MIN_SCALE + (1 - Math.abs(position)) * (MAX_SCALE - MIN_SCALE);
                //  view.setScaleX(scaleFactor);
                //每次滑动后进行微小的移动目的是为了防止在三星的某些手机上出现两边的页面为显示的情况

                view.setScaleY(scaleFactor);

            } else { // (1,+Infinity]

                // view.setScaleX(MIN_SCALE);
                view.setScaleY(MIN_SCALE);

            }
        }
    }

    /**
     * 渐隐效果
     */
    class DepthPageTransformer implements ViewPager.PageTransformer {
        private static final float MIN_SCALE = 0.75f;

        public void transformPage(View view, float position) {
            int pageWidth = view.getWidth();

            if (position < -1) { // [-Infinity,-1)
                // This page is way off-screen to the left.
                view.setAlpha(0);

            } else if (position <= 0) { // [-1,0]
                // Use the default slide transition when moving to the left page
                view.setAlpha(1);
                view.setTranslationX(0);
                view.setScaleX(1);
                view.setScaleY(1);

            } else if (position <= 1) { // (0,1]
                // Fade the page out.
                view.setAlpha(1 - position);

                // Counteract the default slide transition
                view.setTranslationX(pageWidth * -position);

                // Scale the page down (between MIN_SCALE and 1)
                float scaleFactor = MIN_SCALE
                        + (1 - MIN_SCALE) * (1 - Math.abs(position));
                view.setScaleX(scaleFactor);
                view.setScaleY(scaleFactor);

            } else { // (1,+Infinity]
                // This page is way off-screen to the right.
                view.setAlpha(0);
            }
        }
    }


    private void setViewScrollTime(Context context,ViewPager viewpager,int time){
        FixedSpeedScroller mScroller = null;
        try {
            Field mField;

            mField = ViewPager.class.getDeclaredField("mScroller");
            mField.setAccessible(true);

            mScroller = new FixedSpeedScroller(context,
                    new AccelerateInterpolator());
            mScroller.setmDuration(time);
            mField.set(viewpager, mScroller);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }





}
